package com.yunkaweilai.android.base;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.MainActivity;
import com.yunkaweilai.android.utils.StatusBarUtils;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.refresh.BGAStickinessRefreshViewHolder1;
import com.yunkaweilai.android.view.MyToast;

import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * Created by Administrator on 2017-02-21.
 */

public abstract class BaseActivity extends AppCompatActivity {

    protected final String TAG = this.getClass().getSimpleName();
    public BaseApplication mApplication;
    private MaterialDialog mProgress;
    protected BaseActivity mAc;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.wjx_title_bg_next);
        ActivityCollector.addActivity(this);
        if (initExit()) return;
        mApplication = BaseApplication.getInstance();
        mAc = this;

        //初始化友盟 UMConfigure.init(Context context, String appkey, String channel, int deviceType, String pushSecret);
//        UMConfigure.init(mAc,);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(menuItem);
    }


    /**
     * 左侧有返回键的标题栏
     * <p>如果在此基础上还要加其他内容,比如右侧有文字按钮,可以获取该方法返回值继续设置其他内容
     *
     * @param title 标题
     */
    protected TitleBuilder initBackAndTitle(String title) {
        return new TitleBuilder(this)
                .setTitleText(title)
                .setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
    }

    /**
     * 判断是否需要退出app
     *
     * @return
     */
    private boolean initExit() {
        // 如果是退出应用flag,则直接关闭当前页面,不加载UI
        boolean exit = getIntent().getBooleanExtra("exit", false);
        if (exit) {
            finish();
            return true;
        }
        return false;
    }

    /**
     * 退出程序
     */
    protected void exit() {
        // 退出程序方法有多种
        // 这里使用clear + new task的方式清空整个任务栈,只保留新打开的Main页面
        // 然后Main页面接收到退出的标志位exit=true,finish自己,这样就关闭了全部页面
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("exit", true);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 跳转页面,无extra简易型
     *
     * @param tarActivity 目标页面
     */
    public void intent2Activity(Class<? extends Activity> tarActivity) {
        Intent intent = new Intent(this, tarActivity);
        startActivity(intent);
    }

    /**
     * 携带数据的页面跳转
     *
     * @param clz
     * @param bundle
     */
    public void intent2Activity(Class<? extends Activity> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 含有Bundle通过Class打开编辑界面
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void intent2ActivityForResult(Class<?> cls, Bundle bundle,
                                         int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 打印Toast
     *
     * @param msg
     */
    protected void showToast(String msg) {
        MyToast.showShortToast(mAc, msg);
    }

    protected void showToast(int res) {
        MyToast.showShortToast(mAc, res);
    }

    /**
     * 打印Log
     *
     * @param msg
     */
    protected void showLog(String msg) {
        Logger.t(TAG).e(msg);
    }

    /**
     * 展示圆形进度条
     */
    public MaterialDialog showProgressDialog() {
        mProgress = new MaterialDialog.Builder(this)
                //.title(R.string.progress_dialog)
                .content(R.string.progress_content)
                .progress(true, 0)
                .show();
        mProgress.setCanceledOnTouchOutside(false);
        mProgress.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                }
                return false;
            }
        });
        return mProgress;
    }

    public MaterialDialog showProgressDialog(String msg) {
        mProgress = new MaterialDialog.Builder(this)
                //.title(R.string.progress_dialog)
                .content(msg)
                .progress(true, 0)
                .show();
        mProgress.setCanceledOnTouchOutside(false);
        mProgress.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                }
                return false;
            }
        });
//        if (msg.contains("正在支付中")){
//            mProgress.setCanceledOnTouchOutside(false);
//            mProgress.setOnKeyListener(new DialogInterface.OnKeyListener() {
//                @Override
//                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                    if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
//                    {
//                        return true;
//                    }
//                    return false;
//                }
//            });
////            mProgress.setOnCancelListener(new DialogInterface.OnCancelListener() {
////                @Override
////                public void onCancel(DialogInterface dialog) {
////                    dialog.OnKeyListener()
////                }
////            });
//        }
        return mProgress;
    }

    public void setmProgress(String msg) {
        if (mProgress != null) {
            mProgress.setContent(msg);
        }
    }

    /**
     * 关闭圆形进度条
     */
    public void dismissProgressDialog() {
        if (mProgress != null) {
            mProgress.dismiss();
        }
    }


    /**
     * 初始化下拉刷新控件
     *
     * @param refreshLayout 控件
     * @param delegate      实现接口的Activity或Fragment
     * @param isLoading     是否具有上拉加载功能
     */
    public void initRefreshLayout(BGARefreshLayout refreshLayout, BGARefreshLayout.BGARefreshLayoutDelegate delegate, boolean isLoading) {
//        // 为BGARefreshLayout 设置代理
//        refreshLayout.setDelegate(delegate);
//        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
//        BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(mAc, isLoading);
//
//        // 设置下拉刷新和上拉加载更多的风格
//        refreshLayout.setRefreshViewHolder(refreshViewHolder);
//        refreshLayout.setIsShowLoadingMoreView(true);


        // 为BGARefreshLayout 设置代理
        refreshLayout.setDelegate(delegate);
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGAStickinessRefreshViewHolder1 bgaStickinessRefreshViewHolder = new BGAStickinessRefreshViewHolder1(mAc, isLoading);
//        moocStyleRefreshViewHolder.setLoadMoreBackgroundColorRes(R.color.custom_imoocstyle);
        bgaStickinessRefreshViewHolder.setRotateImage(R.mipmap.bga_refresh_stickiness);
        bgaStickinessRefreshViewHolder.setStickinessColor(R.color.wjx_title_bg_next);
        // 设置下拉刷新和上拉加载更多的风格
        refreshLayout.setRefreshViewHolder(bgaStickinessRefreshViewHolder);
        refreshLayout.setIsShowLoadingMoreView(true);
    }

}